<template>
  <el-cascader
    v-model="selectedOptions"
    :options="options"
    :props="cascaderProps"
    :placeholder="placeholder"
    clearable
    @change="handleChange"
    class="no-radio-cascader"
  ></el-cascader>
</template>

<script>
import { regionData, codeToText } from 'element-china-area-data'

export default {
  name: 'FlexibleCascader',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择地区'
    }
  },
  data() {
    return {
      selectedOptions: [],
      options: regionData,
      cascaderProps: {
        value: 'value',
        label: 'label',
        children: 'children',
        checkStrictly: true,  // 必须为true才能任意选择
        emitPath: true,       // 返回完整路径
        expandTrigger: 'hover' // 悬停展开
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.selectedOptions = newVal || []
      }
    }
  },
  methods: {
    handleChange(value) {
      const completePath = this.ensureCompletePath(value)
      this.selectedOptions = completePath
      this.$emit('input', completePath)
      this.$emit('change', this.buildRegionInfo(completePath))
    },
    ensureCompletePath(value) {
      if (!value || value.length === 0) return []
      if (value.length === 3) return value
      if (value.length === 2) {
        return this.options.find(p => p.value === value[0]) ? value : []
      }
      if (value.length === 1) {
        return this.options.find(p => p.value === value[0]) ? value : []
      }
      return []
    },
    buildRegionInfo(codes) {
      const result = {
        provinceCode: "",
        provinceName: "",
        cityCode: "",
        cityName: "",
        districtCode: "",
        districtName: ""
      }
      if (!codes || codes.length === 0) return result
      if (codes.length >= 1) {
        result.provinceCode = codes[0]
        result.provinceName = codeToText[codes[0]] || ""
      }
      if (codes.length >= 2) {
        result.cityCode = codes[1]
        result.cityName = codeToText[codes[1]] || ""
      }
      if (codes.length >= 3) {
        result.districtCode = codes[2]
        result.districtName = codeToText[codes[2]] || ""
      }
      return result
    }
  }
}
</script>

<style>
/* 彻底隐藏单选框 */
.no-radio-cascader .el-cascader-node__prefix,
.no-radio-cascader .el-radio {
  display: none !important;
}

/* 扩大点击区域 */
.no-radio-cascader .el-cascader-node__label {
  padding-left: 20px !important;
  width: 100% !important;
  cursor: pointer;
}

/* 选中状态高亮 */
.no-radio-cascader .el-cascader-node.is-active .el-cascader-node__label {
  color: #409EFF;
  font-weight: bold;
  background: #f5f7fa;
}
</style>